package cn.edu.njnu.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@Component
public class DocProcessor {
    public String extractText(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        if (originalFilename.endsWith(".docx")){
            XWPFDocument document = new XWPFDocument(file.getInputStream());//使用XWPF组件XWPFDocument类获取文档内容
            XWPFWordExtractor extractor = new XWPFWordExtractor(document);
            String text = extractor.getText();
            return text;
        } else if (originalFilename.endsWith(".pptx")) {
            XMLSlideShow ppt = new XMLSlideShow(file.getInputStream());
            StringBuilder stringBuilder = new StringBuilder();
            for (XSLFSlide slide : ppt.getSlides()) {
                for (XSLFShape sh : slide.getShapes()) {
                    if (sh instanceof XSLFTextShape) {
                        XSLFTextShape shape = (XSLFTextShape) sh;
                        stringBuilder.append(shape.getText().trim());
                    }
                }
            }
            return stringBuilder.toString();
        } else if (originalFilename.endsWith(".pdf")) {
            PDDocument document = PDDocument.load(file.getInputStream());
            PDFTextStripper pdfStripper = new PDFTextStripper();
            String text = pdfStripper.getText(document);
            document.close();
            return text;
        } else {
            throw new Exception("格式错误，请上传docx、pptx、pdf格式文件");
        }
    }
}
